<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/26
 * Time: 15:11
 * Desc: 会员登录
 *       1、PC端微信端都是用账号密码登录
 *       2、会员同一个openid可能绑定多账号，不能使用微信授权登录
 */

namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use app\index\controller\Base;
use pinyin\Pinyin;
use app\index\service\WeixinService;

class Login extends Base{
    /**
     * @Author  lingyun
     * @Desc    会员登录
     */
    public function _initialize(){
//        $uid = cookie('_user_uid_.uid');
//        if(!empty($uid)){
//            $user = db('user')->where('uid',$uid)->find();
//            if($user['status'] == 1 && $user['is_deleted'] == 0){
//                session('_user_uid_.uid',$user['uid']);
//                session('_user_uid_.mobile',$user['mobile']);
//                session('_user_uid_.realname',$user['realname']);
//                session('_user_uid_.nickname',$user['nickname']);
//
//                cookie('_user_uid_.uid',$user['uid'],15552000);
//                cookie('_user_uid_.mobile',$user['mobile'],15552000);
//                cookie('_user_uid_.realname',$user['realname'],15552000);
//                cookie('_user_uid_.nickname',$user['nickname'],15552000);
//            }
//        }

        parent::_initialize();
        $ip = request()->ip();                                      //获取客户端的IP地址
        $result = get_location_city($ip);                           //返回当前的城市信息
        $pinyin = new Pinyin();                                     //将中文装换成拼音
        $city_key = $pinyin->getAllPY($result['msg']);              //当前城市的key
        $city = db('city')->where('key',$city_key)->find();         //当前的城市信息
        if(empty($city)){
            $city['value'] = '青岛';
        }
        $this->assign('city',$city);                                //当前城市
        //已登录，直接跳转
//        if(!empty(session('_user_uid_.uid'))){
//            $param = input('param.');
//            if(empty($param['c']) || empty($param['a'])){
//                $url = url('Index/index');
//            }else{
//                $url = input('url');        //上一个页面的url
//            }
//            $this->redirect($url);      //跳转回前一个页面
//        }

    }

    /**
     * @Author  lingyun
     * @Desc    登录
     */
    public function loginin(){
        if(!empty(session('_user_uid_.uid'))){
            if(!empty(input('url'))){
                $url = input('url');
            }else{
                $url = url('Index/index');
            }
            $this->redirect($url);      //跳转回前一个页面
        }
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $where = [
                'password'=>md5($post['password']),
                'mobile'=>$post['mobile']
            ];

            $user = db('user')->where($where)->find();       //会员信息
            //是微信，绑定会员的openID
            if(is_weixin() && empty($user['openid'])){
                db('user')->where('uid',$user['uid'])->update(['openid'=>session('openid')]);
           }else{
                session('openid',$user['openid']);
            }

            if(empty($user)){
                $this->error('手机号或密码错误','');
            }else if($user['status'] == 0){
                $this->error('您的账号已被禁用，如有疑问请联系管理员','');
            }else if($user['is_deleted'] == 1){
                $this->error('该会员已被禁用，如有疑问请联系管理员','');
            }
            session('_user_uid_.uid',$user['uid']);
            session('_user_uid_.mobile',$user['mobile']);
            session('_user_uid_.realname',$user['realname']);
            session('_user_uid_.nickname',$user['nickname']);

            $cookie_data = [
                'uid'=>$user['uid'],
                'mobile'=>$user['mobile'],
                'realname'=>$user['realname'],
                'nickname'=>$user['nickname']
            ];
            cookie('c_user',$cookie_data,15552000);          //记住当前登录人的cookie,用于永久保存会员登录状态

            //记住密码
            if(isset($post['remember'])){
                cookie('login_mobile',$post['mobile'],15552000);
                cookie('login_pass',$post['password'],15552000);
            }

            //微信端保存openID
            if(is_weixin()){
                session('openid',$user['openid']);
            }

            if(!empty($user) && $user['status'] == 0){
                session('user_forbid',1);       //账号已被禁用
            }

            if(!empty($user) && $user['is_deleted'] == 1){
                session('user_forbid',1);       //账号已被禁用
            }

            $this->success('登陆成功','');
        }else{
            $param = input('param.');
            $this->assign('login_mobile',cookie('login_mobile'));
            $this->assign('login_pass',cookie('login_pass'));
            if(!empty(cookie('login_pass'))){
                $this->assign('remember',1);
            }else{
                $this->assign('remember',0);
            }

            if(empty($url)){
                $this->assign('url',input('url'));
            }else {
                $this->assign('url', url('Index/index'));
            }

            return $this->fetch('login');       //登录
        }

    }

    /**
     * @Author  lingyun
     * @Desc    退出登录
     */
    public function logout(){
        session('_user_uid_.uid',null);
        session('_user_uid_.mobile',null);
        session('_user_uid_.realname',null);
        session('_user_uid_.nickname',null);
        session('openid',null);

        cookie('c_user',null);                  //清空会员永久登录状态信息
        $this->redirect('Login/loginin');
    }

    /**
     * @Author  lingyun
     * @Desc    会员注册
     * 赠送积分  A-B-C  A:25  B:50  C:100
     */
    public function register(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $sms_code = session('register_sms_code');
            $msg_mobile = session('register_msg_mobile');
            $send_time = session('register_send_time');
            if(trim($post['realname']) == ''){
                $this->error('请输入真实姓名','');
            }
            if($msg_mobile != trim($post['mobile'])){
                $this->error('手机填写错误','');
            }
            if($sms_code != $post['msg_code']){
                $this->error('验证码输入错误','');
            }
            if($send_time+1800 < time()){
                $this->error('短信验证码已过期，请重新获取','');
            }

            if(!preg_match('/^[a-zA-Z0-9_]{6,16}$/',$post['password'])){
                $this->error('密码格式错误，必须是字母数字下划线6~16组合','');
            }

            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致','');
            }

            $user = db('user')->where('mobile',$post['mobile'])->find();
            if($user['password'] != ''){        //已经注册了
                $this->error('该手机号已被占用，请重新输入','');
            }

//            if(!empty($user)){
//                $this->error('该手机号已被占用，请重新输入','');
//            }

            $point_rule = db('sys_point')->where('code',1)->find();     //会员注册获取积分

            $password = md5($post['password']);
            $data['realname'] = trim($post['realname']);
            $data['nickname'] = trim($post['realname']);
            $data['mobile'] = trim($post['mobile']);
//            $data['level_point'] = $point_rule['point'];
            $data['pay_points'] = $point_rule['point'];
            $data['password'] = $password;
            $data['addtime'] = time();
            if(!empty(cookie('store_id'))){
                $data['store_id'] = cookie('store_id');
            }else{
                $data['store_id'] = 0;
            }

            $data['level_id'] = db('sys_level')->order('score asc')->limit(1)->value('id');     //会员注册默认等级
            if(empty($user)){       //新会员，更新会员
                $res = db('user')->insertGetId($data);

                if(is_weixin()){        //是否是微信端
                    $up_data['openid'] = session('openid');

                    $coupon = db('store_coupon')->where(['store_id'=>cookie('store_id'),'type'=>1,'status'=>1,'is_deleted'=>0])->select();
                    if(!empty($coupon)){
                        foreach($coupon as $k => $v){       //优惠券列表
                            $coupon_arr[$k] = [
                                'store_id'=>$v['store_id'],
                                'uid'=>$res,
                                'coupon_id'=>$v['id'],
                                'type'=>1,
                                'cat_id'=>$v['cat_id'],
                                'condition'=>$v['condition'],
                                'morethan'=>$v['morethan'],
                                'reduce'=>$v['reduce'],
                                'use_start_time'=>$v['use_start_time'],
                                'use_end_time'=>$v['use_end_time'],
                                'addtime'=>time(),
                                'use_end_time'=>$v['use_end_time'],
                            ];
                        }
                        db('user_ycard')->insertAll($coupon_arr);

                        if(is_weixin()){
                            $root = request()->domain();
                            $send_msg = [
                                "type"   	  =>1,
                                "touser" 	  =>session('openid'),
                                "template_id"=>config("weixin_mu_msg.register_msg")["tempid"],
                                "url" 		  =>$root.'/index.php/index/user/my_coupon',
                                "topcolor"  =>"#743A3A",
                                "data"   =>[
                                    "first" 	    =>["value"=>'会员注册成功', "color"=>"#743A3A"],
                                    "keyword1"		=>["value"=>$data['mobile'], 		"color"=>"#743A3A"],
                                    "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                    "remark"		=>["value"=>"会员注册成功，已获得优惠券，请到会员中心查看", 			"color"=>"#743A3A"],
                                ]
                            ];
                            $this->sendMessage($send_msg);
                        }
                    }
                }

                //更新数据
                if(is_weixin()){        //是否是微信端
                    $up_data['openid'] = session('openid');
                }

                $up_data['pay_code'] = get_pay_code($res);      //会员支付码
                db('user')->where('uid',$res)->update($up_data);        //更新会员支付码、会员openID
            }else{
                $res = db('user')->where('mobile',$post['mobile'])->update($data);
                if(is_weixin()){        //是否是微信端
                    $up_data['openid'] = session('openid');
                    db('user')->where('mobile',$post['monile'])->update($up_data);        //更新会员支付码、会员openID
                }
            }




            $point_arr = [
                'uid'=>$res,
                'uidtype'=>3,
                'signid'=>4,
                'type'=>1,
                'point'=>$point_rule['point'],
                'curpoint'=>$point_rule['point'],
                'type_cn'=>'注册会员赠送积分',
                'remark'=>'注册会员赠送积分',
                'addtime'=>time(),
                'tuijianrenuid'=>0
            ];
            db('user_point_log')->data($point_arr)->insert();       //更新会员积分记录

            if($res !== false){
                session('_user_uid_.uid',$res);
                session('_user_uid_.mobile',$post['mobile']);
                session('_user_uid_.realname',$post['realname']);
                session('_user_uid_.nickname',$post['realname']);

                $cookie_data = [
                    'uid'=>$res,
                    'mobile'=>$post['mobile'],
                    'realname'=>$post['realname'],
                    'nickname'=>$post['realname']
                ];
                cookie('c_user',$cookie_data,15552000);          //记住当前登录人的cookie

                //微信端保存openID
                if(is_weixin()){
                    session('openid',$user['openid']);
                }else{      //pc端openid是null
                    session('openid',null);
                }
                $this->success('密码修改成功','');
            }else{
                $this->error('密码修改失败','');
            }

        }else{
            return $this->fetch('register');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    忘记密码
     */
    public function find_password(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $sms_code = session('sms_code');
            $msg_mobile = session('msg_mobile');
            $send_time = session('send_time');
            if($msg_mobile != $post['mobile']){
                $this->error('手机填写错误','');
            }
            if($sms_code != $post['msg_code']){
                $this->error('验证码输入错误','');
            }
            if($send_time+1800 < time()){
                $this->error('短信验证码已过期，请重新获取','');
            }

            if(!preg_match('/^[a-zA-Z0-9_]{6,16}$/',$post['password'])){
                $this->error('密码格式错误，必须是字母数字下划线6~16组合','');
            }

            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致','');
            }

            $user = db('user')->where('mobile',$post['mobile'])->find();

            if(empty($user)){
                $this->error('找不到会员信息，请检查手机号输入是否正确','');
            }
            if($user['status'] == 0 || $user['is_deleted'] == 1){
                $this->error('您的账号已被禁用，如有疑问请联系管理员','');
            }

            $password = md5($post['password']);
            $res = db('user')->where('mobile',$post['mobile'])->update(['password'=>$password]);
            //是微信，绑定会员的openID
            if(is_weixin() && empty($user['openid'])){
                db('user')->where('uid',$user['uid'])->update(['openid'=>session('openid')]);
            }else{
                session('openid',$user['openid']);
            }
            if($res !== false){
                session('_user_uid_.uid',$user['uid']);
                session('_user_uid_.mobile',$user['mobile']);
                session('_user_uid_.realname',$user['realname']);
                session('_user_uid_.nickname',$user['nickname']);
                cookie('login_mobile',$user['mobile'],15552000);
                cookie('login_pass',$post['password'],15552000);
                $this->success('密码修改成功','');
            }else{
                $this->error('密码修改失败','');
            }

        }else{
            return $this->fetch('find_password');
        }
    }



    /**
     * @Author  lingyun
     * @Desc    获取短信验证码 -- 找回密码时获取短信验证码
     */
    public function get_sms_code(){
        $mobile = input('mobile');      //获取手机号
        $send_time = session('send_time');
        if(!empty($send_time) && $send_time+60>time()){
            $this->error('验证码请求过于频繁，请稍后再试','');
        }
        $code = rand(100000,999999);
        $response = \SMS::sendSms(config('alidayu.msg_sign'),config('alidayu.msg_template'),$mobile,array("code"=>$code)
        );

        if($response->Code == 'OK'){
            session('sms_code',$code);
            session('msg_mobile',$mobile);
            session('send_time',time());
//            Cache::set('18765227746'.'sms_code',868686,60);
            $this->success('发送成功','',array('code'=>$code));
        }else{
            $this->error('发送失败','');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    获取短信验证码 -- 会员注册时获取短信验证码
     */
    public function get_msg_code(){
        $mobile = input('mobile');      //获取手机号
        $send_time = session('register_send_time');
        if(!empty($send_time) && $send_time+60>time()){
            $this->error('验证码请求过于频繁，请稍后再试','');
        }
        $code = rand(100000,999999);
        $response = \SMS::sendSms(
            "阿里云短信测试专用", // 短信签名
            "SMS_133979742", // 短信模板编号
            $mobile, // 短信接收者
            array(  // 短信模板中字段的值
                "code"=>$code,
            )
        );
        if($response->Code == 'OK'){
            session('register_sms_code',$code);
            session('register_msg_mobile',$mobile);
            session('register_send_time',time());
//            Cache::set('18765227746'.'sms_code',868686,60);
            $this->success('发送成功','',array('code'=>$code));
        }else{
            $this->error('发送失败','');
        }
    }

    /**
     * @Author lignyun
     * @Desc    推送模板消息
     */
    private function sendMessage($array){
        $wein = new WeixinService();
        $rest  = $wein->sendmsg($array);
    }

}